package com.inibb.app.validator;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.validation.ValidationContext;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;

import com.inibb.app.exception.ServiceVLDException;
import com.inibb.app.validator.JpaValidatorHelper;
import com.inibb.app.vo.security.UserVO;



@Component
public class UserValidator {
	@Autowired
	private Validator validator;

	public void validateInput(UserVO userDTO, ValidationContext context){
		Set<ConstraintViolation<UserVO>> errs = validator.validate(userDTO);
		if(errs.isEmpty()){
			return;
		}else{
			ServiceVLDException exp = JpaValidatorHelper.convertToException(errs, userDTO, "user");
			for(Object err: exp.getAllErrors()){
				FieldError oerr = (FieldError) err;
				context.getMessageContext().addMessage(new MessageBuilder().error().code(oerr.getCode()).source(oerr.getField()).
			                defaultText(oerr.getDefaultMessage()).args(oerr.getArguments()).build());
			}
		}
	}
}
